package com.starbaba.loanbusiness.service.impl;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.loanbusiness.model.LoanBusinessModel;
import com.starbaba.loanbusiness.model.LoanBusinessTempModel;
import com.starbaba.loanbusiness.service.LoanBusinessService;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.utils.DateUtils;

@SuppressWarnings("rawtypes")
public class LoanBusinessServiceImpl implements LoanBusinessService{
	
	@SuppressWarnings("deprecation")
    private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	@Override
	public List<?> getDataList(int iDisplayStart, int iDisplayLength, PageResponse pageResponse, Map<String, Object> paramsMap) {
		
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String operator = (String) paramsMap.get("operator");
		String dataType = (String) paramsMap.get("dataType");
		String sourceId = (String) paramsMap.get("sourceId");
		String prdId = (String) paramsMap.get("prdid");
		String source = (String) paramsMap.get("source");
		String userName = (String)paramsMap.get("userName");
		String isManager = (String)paramsMap.get("isManager");

		StringBuffer sql = new StringBuffer();
		sql.append("select a.id,a.source_id, a.type,a.register, a.apply, a.success,b.name activity_name,");
		sql.append("a.money_count,a.total_amount, a.settle_amount, a.operator,csv_date, a.ctime, a.prdid ");
		
		if (StringUtils.isEmpty(source) || "1".equals(source)) {
			sql.append("from loan_api_import_record a ");
			sql.append("left join loan_product_info b on (a.source_id = b.id) ");
		} else {
			sql.append("from loan_api_import_record_temp a ");
			sql.append("left join loan_product_info b on (a.source_id = b.id) ");
		}
		
		sql.append(" where 1=1 ");

		String selectSql = "";

		if ("true".equals(isManager)) {
			// 查询所有人的记录
			if (StringUtils.isNotEmpty(operator)) {
				selectSql += " and a.operator = '" + operator + "'";
			}
		} else {
			selectSql += " and a.operator = '" + userName + "'";
		}

		if (StringUtils.isNotEmpty(startTime)) {
			selectSql += " and a.csv_date >= '" + startTime + " 00:00:00'";
		}
		if (StringUtils.isNotEmpty(endTime)) {
			selectSql += " and a.csv_date <= '" + endTime + " 23:59:59'";
		}
		if (StringUtils.isNotEmpty(dataType)) {
			selectSql += " and a.type = '" + dataType + "'";
		}
		if (StringUtils.isNotEmpty(sourceId)) {
			selectSql += " and a.source_id = '" + sourceId + "'";
		}
		if (StringUtils.isNotEmpty(prdId)) {
			selectSql += " and a.prdid = '" + prdId + "'";
		}

		sql.append(selectSql);
		sql.append(" order by a.ctime desc ");

		if (sql.length() > 0 && iDisplayStart >= 0 && iDisplayLength > 0) {
			sql.append(" limit " + iDisplayStart + " , " + iDisplayLength);
		}

		List<?> list = null;
		
		try {
			int count = 0;
			StringBuffer strSql = new StringBuffer();
			if (StringUtils.isEmpty(source) || "1".equals(source)) {
				strSql.append("select count(1) from loan_api_import_record a ");
				strSql.append("left join loan_product_info b on (a.source_id = b.id) where 1=1 ");
				strSql.append(selectSql);
				count = dao.getInt(strSql.toString());
				list = dao.list(sql.toString(), LoanBusinessModel.class, new Object[] {});
			} else {
				strSql = new StringBuffer();
				strSql.append("select count(1) from loan_api_import_record_temp a ");
				strSql.append("left join loan_product_info b on (a.source_id = b.id) where 1=1 ");
				strSql.append(selectSql);
				count = dao.getInt(strSql.toString());
				list = dao.list(sql.toString(), LoanBusinessTempModel.class, new Object[] {});
			}
			pageResponse.setITotalRecords(count);
			pageResponse.setITotalDisplayRecords(count);
		} catch (AppException e) {
			e.printStackTrace();
		}
		return list;
	}
 
	@Override
	public List<LoanBusinessModel> getWeekDataList(int iDisplayStart, int iDisplayLength, PageResponse pageResponse, 
			Map<String, Object> paramsMap) throws ParseException {
		
		List<LoanBusinessModel> resultList = new ArrayList<LoanBusinessModel>();

		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String dataType = (String) paramsMap.get("dataType");
		String sourceId = (String) paramsMap.get("sourceId");
		String prdId = (String) paramsMap.get("prdid");
		String operator = (String) paramsMap.get("operator");
		String userName = (String)paramsMap.get("userName");
		String isManager = (String)paramsMap.get("isManager");

		if (StringUtils.isEmpty(startTime)) {
			startTime = String.valueOf(LocalDate.now());
		}

		if (StringUtils.isEmpty(endTime)) {
			endTime = String.valueOf(LocalDate.now());
		}

		try {
			List<String> weekList = DateUtils.getWeekList(startTime, endTime);

			for (int i = 0; i < weekList.size(); i++) {
				
				StringBuffer sql = new StringBuffer();
				sql.append("select a.id, a.source_id, a.type, sum(a.register) register, sum(a.apply) apply, sum(a.success) success, ");
				sql.append("sum(a.money_count) money_count,sum(a.total_amount) total_amount, sum(a.settle_amount) settle_amount,b.name activity_name,");
				sql.append("a.operator, a.csv_date, a.ctime, a.prdid from loan_api_import_record a left join loan_product_info b on (a.source_id = b.id) ");
				sql.append("where a.csv_date between ? and ? ");

				String selectSql = "";
				
				if ("true".equals(isManager)) {
					// 查询所有人的记录
					if (StringUtils.isNotEmpty(operator)) {
						selectSql += " and a.operator = '" + operator + "'";
					}
				} else {
					selectSql += " and a.operator = '" + userName + "'";
				}
				
				if (StringUtils.isNotEmpty(dataType)) {
					selectSql += " and a.type = '" + dataType + "'";
				}
				if (StringUtils.isNotEmpty(sourceId)) {
					selectSql += " and a.source_id = '" + sourceId + "'";
				}
				if (StringUtils.isNotEmpty(prdId)) {
					selectSql += " and a.prdid = '" + prdId + "'";
				}
				sql.append(selectSql);
				sql.append(" order by a.ctime desc ");
				if (sql.length() > 0 && iDisplayStart >= 0 && iDisplayLength > 0) {
					sql.append(" limit " + iDisplayStart + " , " + iDisplayLength);
				}

				String[] arrDate = weekList.get(i).split("~");

				LoanBusinessModel model = dao.get(sql.toString(), LoanBusinessModel.class, arrDate[0], arrDate[1]);

				if (model != null) {
					model.setCsv_date(weekList.get(i));
					resultList.add(model);
				}
			}
			pageResponse.setITotalRecords(resultList.size());
			pageResponse.setITotalDisplayRecords(resultList.size());
		} catch (AppException e) {
			e.printStackTrace();
		}
		return resultList;
	}

	@Override
	public List<LoanBusinessModel> getMonthDataList(int iDisplayStart, int iDisplayLength, PageResponse pageResponse, 
			Map<String, Object> paramsMap) {
		
		List<LoanBusinessModel> resultList = new ArrayList<LoanBusinessModel>();

		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String operator = (String) paramsMap.get("operator");
		String dataType = (String) paramsMap.get("dataType");
		String sourceId = (String) paramsMap.get("sourceId");
		String prdId = (String) paramsMap.get("prdid");
		String userName = (String)paramsMap.get("userName");
		String isManager = (String)paramsMap.get("isManager");

		if (StringUtils.isEmpty(startTime)) {
			startTime = String.valueOf(LocalDate.now());
		}

		if (StringUtils.isEmpty(endTime)) {
			endTime = String.valueOf(LocalDate.now());
		}

		try {
			List<String> monthList = DateUtils.getMonthList(startTime, endTime);

			for (int i = 0; i < monthList.size(); i++) {
				
				StringBuffer sql = new StringBuffer();
				sql.append("select a.id, a.source_id, a.type, sum(a.register) register, sum(a.apply) apply, sum(a.success) success, ");
				sql.append("sum(a.money_count) money_count, sum(a.total_amount) total_amount, sum(a.settle_amount) settle_amount,b.name activity_name,");
				sql.append("a.operator, a.csv_date, a.ctime, a.prdid from loan_api_import_record a left join loan_product_info b on (a.source_id = b.id) ");
				sql.append("where a.csv_date between ? and ? ");

				String selectSql = "";
				
				if ("true".equals(isManager)) {
					// 查询所有人的记录
					if (StringUtils.isNotEmpty(operator)) {
						selectSql += " and a.operator = '" + operator + "'";
					}
				} else {
					selectSql += " and a.operator = '" + userName + "'";
				}
				
				if (StringUtils.isNotEmpty(dataType)) {
					selectSql += " and a.type = '" + dataType + "'";
				}
				if (StringUtils.isNotEmpty(sourceId)) {
					selectSql += " and a.source_id = '" + sourceId + "'";
				}
				if (StringUtils.isNotEmpty(prdId)) {
					selectSql += " and a.prdid = '" + prdId + "'";
				}
				sql.append(selectSql);
				sql.append(" order by a.ctime desc ");
				if (sql.length() > 0 && iDisplayStart >= 0 && iDisplayLength > 0) {
					sql.append(" limit " + iDisplayStart + " , " + iDisplayLength);
				}

				String[] arrDate = monthList.get(i).split("~");

				LoanBusinessModel model = dao.get(sql.toString(), LoanBusinessModel.class, arrDate[0], arrDate[1]);

				if (model != null) {
					model.setCsv_date(monthList.get(i));
					resultList.add(model);
				}
			}
			pageResponse.setITotalRecords(resultList.size());
			pageResponse.setITotalDisplayRecords(resultList.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultList;
	}
     
	
	@Override
	public String exportLoanDataList(List<LoanBusinessModel> list) {

		DecimalFormat format = new DecimalFormat("0.00");
		format.setRoundingMode(RoundingMode.HALF_UP);

		StringBuffer sf = new StringBuffer();
		sf.append("日期,创建人,合作方ID,合作方名称,所属类型,产品,注册数,申请数,进件成功数,出额数,总出额金额,结算金额,件单价,甲方放款成本\r\n");

		for (LoanBusinessModel vo : list) {

			sf.append("'" + vo.getCsv_date()).append(",");
			sf.append(vo.getOperator()).append(",");
			Long sourceId = vo.getSource_id();
			sf.append("'" + sourceId).append(",");
			sf.append(vo.getActivity_name()).append(",");
			
			Integer type = vo.getType();
			if (type != null) {
				if (type == 1) {
					sf.append("站内").append(",");
				} else if (type == 2) {
					sf.append("短信").append(",");
				} else if (type == 3) {
					sf.append("推广").append(",");
				} else if (type == 4) {
					sf.append("公众号").append(",");
				} else if (type == 5) {
					sf.append("外部联登").append(",");
				} else {
					sf.append("--").append(",");
				}
			}

			String prdId = vo.getPrdid();

			if ("8000".equals(prdId)) {
				sf.append("菠萝贷主包").append(",");
			} else if ("8001".equals(prdId)) {
				sf.append("极速借钱").append(",");
			} else if ("8002".equals(prdId)) {
				sf.append("菠萝贷ios").append(",");
			} else if ("8003".equals(prdId)) {
				sf.append("手机现金侠").append(",");
			} else if ("8004".equals(prdId)) {
				sf.append("借了么").append(",");
			} else if ("8005".equals(prdId)) {
				sf.append("菠萝贷ios新").append(",");
			} else if ("8006".equals(prdId)) {
				sf.append("联登外部页").append(",");
			} else if ("8100".equals(prdId)) {
				sf.append("微信菠萝贷").append(",");
			} else if ("8200".equals(prdId)) {
				sf.append("香蕉还卡主包").append(",");
			} else if ("8300".equals(prdId)) {
				sf.append("速来贷").append(",");
			} else {
				sf.append("--").append(",");
			}

			sf.append(vo.getRegister()).append(",");
			sf.append(vo.getApply()).append(",");
			sf.append(vo.getSuccess()).append(",");
			sf.append(vo.getMoney_count()).append(",");
			sf.append(vo.getTotal_amount()).append(",");
			sf.append(vo.getSettle_amount()).append(",");
			
			String totalAmount = vo.getTotal_amount();
			Integer moneyCount = vo.getMoney_count();
			String settleAmount = vo.getSettle_amount();
			
			if (totalAmount != null && moneyCount != null) {
				sf.append(format.format(Double.parseDouble(totalAmount) / moneyCount)).append(",");
			} else {
				sf.append(0).append(",");
			}

			if (settleAmount != null && moneyCount != null) {
				sf.append(format.format(Double.parseDouble(settleAmount) / moneyCount)).append(",");
			} else {
				sf.append(0).append(",");
			}
			sf.append("\r\n");
		}
		return sf.toString();
	}
}
